import plugin from '../../../lib/plugins/plugin.js'
import fetch from 'node-fetch'

export class btSearch extends plugin {
  constructor() {
    super({
      /** 功能名称 */
      name: '搜磁力',
      /** 功能描述 */
      dsc: '通过名称搜索磁力猫网站磁力链接',
      event: 'message',
      /** 优先级，数字越小等级越高 */
      priority: 1000,
      rule: [
        {
          /** 命令正则匹配 */
          reg: '^#*搜磁力(.*)$',
          /** 执行方法 */
          fnc: 'btsearch'
        }
      ]
    })
  }

  /**
   * 
   */
  async btsearch(e) {

    let emsg = e.msg.replace(/#|＃|搜磁力/g, "");

    let url = "https://xn--tfrs17es0d.com/"; //获取最新接口地址
    let response = await fetch(url);
    let res = await response.text(); //获取页面内容
    let urlnew = res.match(/<a href="(http[s]?:\/\/.*?)"/g);
    // console.log(urlnew);
    if (!urlnew || urlnew.length <= 0) {
      await this.reply("服务似乎开小差了，等会再试试吧。");
      return true;
    }
    
    // console.log(Math.ceil(Math.random() * urlnew.length));
    

    urlnew = urlnew[Math.ceil(Math.random() * urlnew.length)].replace(/<a href="|"|'/g, "");
    // console.log(urlnew);

    if (!emsg || emsg.length <= 0) {
      await this.reply("请输入需要搜索的内容 [#搜磁力xxx]");
      return true;
    }
    let btSearchurl = urlnew + `/search-${emsg}-0-0-1.html`;
    let responseBt = await fetch(btSearchurl);
    let resBt = await responseBt.text(); //获取页面内容
    let magnetBt = resBt.match(/<a href="(magnet.*?)"/g);
    if (!magnetBt || magnetBt.length <= 0) {
      await this.reply("没有找到相关的磁力资源！");
      return true;
    }
    try {
      let title = resBt.replace(/[\r\n]/g, "").match(/<div class="title"(.*?)div>/g);
      title = title[0].replace(/<.*?>/g, "").replace(/\ +/g, "");
      if (title.match(/高潮|喷水|无码|流出|做爱|操|插入|裸体|自慰|下贱|下体|湿蒂|插|呻吟/g)) {
        title = "神秘标题过于神秘无法展示";
      }
      magnetBt = magnetBt[0].replace(/<a href="|"|'/g, "");
      await this.reply("[神秘标题]:\n" + title + "\n[神秘代码]:\n" + magnetBt);
    }
    catch (err) {
      await this.reply(`出现了一些神秘的错误`);
    }
  }
}
